package com.lhb.gateway.filter;


import com.lhb.common.exception.UnauthorizedException;
import com.lhb.gateway.config.AuthProperties;
import com.lhb.gateway.utils.CollUtils;
import com.lhb.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否不需要拦截
        if(isExclude(request.getPath().toString())){
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 3.获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(headers)) {
            token = headers.get(0);
        }
        // 4.校验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            // 根据异常消息定制响应体
            String errorMessage;
            if (e.getMessage().contains("未登录")) {
                errorMessage = "未登录,请登录后再试";
            } else if (e.getMessage().contains("token已经过期")) {
                errorMessage = "登录过期，请重新登录";
            } else {
                errorMessage = "登录信息无效，请重新登录";
            }

            // 构建JSON响应体
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            byte[] body = ("{\"code\": 401, \"message\": \"" + errorMessage + "\"}").getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(body);

            return response.writeWith(Mono.just(buffer));
        }

        // TODO 5.如果有效，传递用户信息
        System.out.println("userId = " + userId);

        // 5. 将用户 ID 添加到请求头中
        ServerHttpRequest modifiedRequest = request.mutate()
                .header("USER_ID", userId.toString()) // 添加自定义请求头
                .build();

        // 6. 使用修改后的请求创建新的 Exchange
        ServerWebExchange modifiedExchange = exchange.mutate().request(modifiedRequest).build();
        // 6.放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}